package com.cnap.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * <类文件描述>
 *
 * @author xc
 **/
public final class JsonUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(JsonUtil.class);
    private static final ObjectMapper MAPPER = new ObjectMapper();

    private static final String STANDARD_PATTERN = "yyyy-MM-dd HH:mm:ss";

    static {
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        // 日期格式
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(STANDARD_PATTERN);
        // 序列化
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(dateTimeFormatter));
        // 反序列化
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(dateTimeFormatter));
        // 注册
        MAPPER.registerModule(javaTimeModule);

        MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    private JsonUtil() {
    }

    /**
     * 转jsonstr
     *
     * @param data 对象
     * @return jsonstr
     */
    public static String objectToJsonStr(Object data) {
        try {
            return MAPPER.writeValueAsString(data);
        } catch (JsonProcessingException e) {
            LOGGER.error("parse object to json error: {}", e.getMessage());
        }
        return null;
    }

    /**
     * jsonStr转对象
     *
     * @param jsonStr  字符串
     * @param beenType 类型
     * @param <T>      类型
     * @return 对象
     */
    public static <T> T jsonStrToObject(String jsonStr, Class<T> beenType) {
        try {
            return MAPPER.readValue(jsonStr, beenType);
        } catch (JsonProcessingException e) {
            LOGGER.error("parse json to object error: {}", e.getMessage());
        }
        return null;
    }

    /**
     * jsonStr转对象
     *
     * @param jsonStr       字符串
     * @param typeReference typeReference
     * @param <T>           T
     * @return 对象
     */
    public static <T> T jsonStrToObject(String jsonStr, TypeReference<T> typeReference) {
        try {
            return MAPPER.readValue(jsonStr, typeReference);
        } catch (JsonProcessingException e) {
            LOGGER.error("parse json to object error: {}", e.getMessage());
        }
        return null;
    }
}
